package com.hj.system.system.service.impl;

import com.hj.system.base.annotation.CacheRemove;
import com.hj.system.base.utils.PageUtils;
import com.hj.system.system.dao.RoleDao;
import com.hj.system.system.domain.RoleDO;
import com.hj.system.system.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleMapper;

    @Override
    public PageUtils list(Map<String, Object> map) {
        return PageUtils.getPageUtils(roleMapper, map);
    }

    @Override
    public Set<String> listUserRoleIds(String userId) {
        List<String> rolesIds = roleMapper.rolesIdsByUserId(userId);
        return new HashSet<>(rolesIds);
    }

    @Transactional
    @Override
    @CacheRemove(value = "menus",key = {"userId","menuId"})
    public int grantPermissions(String[] menus, String roleId) {
        RoleDO roleDO = new RoleDO();
        roleDO.setRoleId(roleId);
        roleDO.setMenuIds(Arrays.asList(menus));
        roleMapper.removeMenusByRoleId(roleId);
        return roleMapper.grantPermission(roleDO);
    }

    @Override
    public List<RoleDO> listUserRoles(String userId) {
        List<RoleDO> roles = roleMapper.list(new HashMap<>());
        if (!"".equalsIgnoreCase(userId) && userId != null) {
            List<String> rolesIds = roleMapper.rolesIdsByUserId(userId);
            for (RoleDO roleDO : roles) {
                roleDO.setRoleSign("0");
                for (String roleId : rolesIds) {
                    if (Objects.equals(roleDO.getRoleId(), roleId)) {
                        roleDO.setRoleSign("1");
                        break;
                    }
                }
            }
        }
        return roles;
    }

    @Transactional
    @Override
    public int save(RoleDO role) {
        int count = roleMapper.save(role);
        return count;
    }

    @Transactional
    @Override
    public int remove(String id) {
        int count = roleMapper.remove(id);
        roleMapper.removeMenusByRoleId(id);
        return count;
    }


    @Override
    public RoleDO get(String id) {
        RoleDO roleDO = roleMapper.get(id);
        return roleDO;
    }

    @Override
    public int update(RoleDO role) {
        int r = roleMapper.update(role);
        return r;
    }

    @Override
    public int batchRemove(String[] ids) {
        int r = roleMapper.batchRemove(ids);
        return r;
    }


}
